package com.itheima.d4_create_thread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 目标：掌握线程的创建方式三：实现Callable接口。
 */
public class ThreadTest3 {
    public static void main(String[] args) throws Exception {
        //创建FutureTask对象,传入Callable子类对象
        MyCallable myCallable = new MyCallable(100);
        FutureTask<Long> futureTask = new FutureTask<>(myCallable);
        //创建线程对象,传入futureTask任务,调用start方法开启线程
        Thread thread = new Thread(futureTask);
        thread.start();

        //获取线程执行的结果
        System.out.println(futureTask.get());
    }
}

class MyCallable implements Callable<Long> {

    private  long n;

    public MyCallable() {
    }

    public MyCallable(long n) {
        this.n = n;
    }

    @Override
    public Long call() throws Exception {
        long sum =0;
        for (long i = 1; i <= n; i++) {
            sum +=i;
        }
        return sum;
    }
}